import { Button, Switch, Table, Modal, message, Descriptions, Form, Input, Space } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import { ColumnsType } from 'antd/lib/table';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { SeatInfo } from '../../../schema/Seat';
import { delSeat, enableSeatUser, getSeatList, resetSeatPwd } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { SeatOperation } from './component/SeatOperation';
import ResetPassword from 'admin/components/ResetPassword';

interface UserState {
  tableData: SeatInfo[];
  resetPwdVisible: boolean;
  checkDetailVisible: boolean;
  currentRecord: SeatInfo;
  searchForm: any;
  pageInfo: {
    pageNum: number;
    pageSize: number;
    pageTotal: number;
  };
  tableLoading: boolean;
}

export default class Seat extends React.Component<{}, UserState> {
  // table 列
  columns: ColumnsType<SeatInfo>;
  formRef = React.createRef<FormInstance>();

  // 用户操作控件引用
  SeatOperationRef: React.RefObject<SeatOperation>;

  resetPwdForm: React.RefObject<FormInstance>;

  // 已选id
  selectedIds: number[];

  constructor(props: {}) {
    super(props);
    this.SeatOperationRef = React.createRef();
    this.resetPwdForm = React.createRef();
    this.selectedIds = [];
    this.state = {
      tableData: [],
      resetPwdVisible: false,
      checkDetailVisible: false,
      searchForm: {},
      currentRecord: {} as SeatInfo,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };
    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '坐席姓名',
        dataIndex: 'nickName',
        key: 'nickName',
      },
      {
        title: '账号',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '坐席工号',
        dataIndex: 'seatsNumber',
        key: 'seatsNumber',
      },
      {
        title: '组织机构名称',
        dataIndex: 'organizationName',
        key: 'organizationName',
      },
      {
        title: '状态',
        dataIndex: 'userStatus',
        key: 'userStatus',
        render: (text, record, index) => {
          return (
            <>
              <Switch
                disabled={!checkPermission('/account/seat/status')}
                checked={record.userStatus === 0}
                onChange={enable => {
                  this.setSeatUserEnable(enable, record);
                }}
              />
            </>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 320,
        render: (text, record, index) => {
          return (
            <>
              <Button
                type="link"
                onClick={() => {
                  this.checkDetail(record);
                }}
              >
                详情
              </Button>
              {checkPermission('/account/seat/modify') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.modify(record);
                  }}
                >
                  编辑
                </Button>
              )}
              {checkPermission('/account/seat/resetPwd') && (
                <Button type="link" onClick={() => this.showResetModal(record)}>
                  重置密码
                </Button>
              )}
              {checkPermission('/account/seat/delete') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.deleteRecord(record);
                  }}
                >
                  删除
                </Button>
              )}
            </>
          );
        },
      },
    ];
    this.handleResetPwdRequest = this.handleResetPwdRequest.bind(this);
    this.closeResetModal = this.closeResetModal.bind(this);
  }

  componentDidMount() {
    this.fetchList();
  }

  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };

  /**
   * 查看用户详情交互
   */
  private checkDetail(record: SeatInfo): void {
    this.setState({
      checkDetailVisible: true,
      currentRecord: record,
    });
  }

  /**
   * 编辑用户交互
   */
  private modify(record: SeatInfo): void {
    this.SeatOperationRef.current?.open('modify', record);
  }

  /**
   * 显示重置密码弹窗
   * @param record
   */
  private showResetModal(record: SeatInfo): void {
    this.setState({
      resetPwdVisible: true,
      currentRecord: record,
    });
  }

  /**
   * 发送重置密码请求
   */
  private async handleResetPwdRequest(newPassword: string) {
    const { userId, userName } = this.state.currentRecord;
    try {
      await resetSeatPwd({
        userId: userId,
        userName: userName,
        passWord: newPassword,
      });
      message.success('密码重置成功');
      this.closeResetModal();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }
  /**
   * 关闭重置密码弹窗
   */
  closeResetModal() {
    this.setState({ resetPwdVisible: false });
  }
  /**
   * 删除表格行数据后，当前页刷新
   * @param size 条数
   */
  private freshTableDelRow(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * 删除用户
   */
  private deleteRecord(record: SeatInfo): void {
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        delSeat(record.userId as number)
          .then(res => {
            message.success('删除成功');
            this.freshTableDelRow(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 停用/启用 用户-坐席端登录权限
   */
  private setSeatUserEnable(enable: boolean, record: SeatInfo): void {
    if (!enable) {
      Modal.confirm({
        content: '确定停用账号吗，停用后此账户将无法登录系统',
        onOk: () => {
          enableSeatUser(record.userId as number, {
            userStatus: 1,
          })
            .then(res => {
              message.success('停用成功');
              this.fetchList();
            })
            .catch(error => {
              console.error(`系统异常: ${JSON.stringify(error)}`);
            });
        },
      });
    } else {
      enableSeatUser(record.userId as number, {
        userStatus: 0,
      })
        .then(res => {
          message.success('启用成功');
          this.fetchList();
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    }
  }
  /**
   * 查询操作，提交查询条件
   */
  handleSearch = (values: any) => {
    this.setState(
      {
        searchForm: { ...values },
      },
      () => {
        this.jumpPage(1);
      }
    );
  };

  /**
   * 重置查询操作
   */
  handleReset = () => {
    this.formRef.current?.resetFields();
    this.setState(
      {
        searchForm: {},
      },
      () => {
        this.jumpPage(1);
      }
    );
  };

  /**
   * 查询当前列表
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo, searchForm } = this.state;
    const params = {
      ...searchForm,
      pageNo: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    };
    getSeatList(clearNull(params))
      .then(res => {
        this.setState({
          tableLoading: false,
        });
        const { count, data } = res;
        pageInfo.pageTotal = count || 0;
        this.setState({
          tableData: data || [],
          pageInfo: pageInfo,
        });
      })
      .catch(error => {
        this.setState({
          tableLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 表格行操作后，重置列表
   */
  private resetList() {
    this.jumpPage(1);
  }
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }
  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
      resetPwdVisible,
      checkDetailVisible,
      currentRecord,
    } = this.state;
    const { columns, SeatOperationRef } = this;
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.selectedIds = [];
        selectedRows.forEach((item: any) => {
          this.selectedIds.push(item.userId);
        });
      },
    };
    return (
      <div className="user-mgr">
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Form layout="inline" ref={this.formRef} onFinish={this.handleSearch}>
              <Form.Item
                label=""
                name="condition"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input allowClear placeholder="请输入账号/坐席工号" />
              </Form.Item>
              <Form.Item
                label="坐席姓名"
                name="nickName"
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input allowClear placeholder="请输入" />
              </Form.Item>
              <Space size="middle">
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button type="primary" ghost onClick={this.handleReset}>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className="mgr-header-right">
            {checkPermission('/account/seat/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.SeatOperationRef.current?.open('create');
                }}
              >
                新建坐席
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            scroll={{ x: 'max-content' }}
            rowSelection={{ type: 'checkbox', ...rowSelection }}
            columns={columns}
            dataSource={tableData}
            rowKey="userId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <ResetPassword
          visible={resetPwdVisible}
          userName={currentRecord.userName}
          submitFn={this.handleResetPwdRequest}
          closeFn={this.closeResetModal}
        />
        <Modal
          width={650}
          className="user-check-detail"
          title="坐席详情"
          visible={checkDetailVisible}
          footer={null}
          onCancel={() => {
            this.setState({ checkDetailVisible: false });
          }}
        >
          <Descriptions column={2}>
            <Descriptions.Item label="账号">{currentRecord.userName}</Descriptions.Item>
            <Descriptions.Item label="坐席姓名">{currentRecord.nickName}</Descriptions.Item>
            <Descriptions.Item label="性别">
              {currentRecord?.sex ? '女' : currentRecord?.sex === 0 ? '男' : '--'}
            </Descriptions.Item>
            <Descriptions.Item label="企业">{currentRecord.companyName}</Descriptions.Item>
            <Descriptions.Item label="组织架构">{currentRecord.organizationName}</Descriptions.Item>
            <Descriptions.Item label="手机号">{currentRecord.mobile}</Descriptions.Item>
            <Descriptions.Item label="身份证号">
              {currentRecord.idCardNumber || '--'}
            </Descriptions.Item>
            <Descriptions.Item label="邮箱">{currentRecord.email || '--'}</Descriptions.Item>
            <Descriptions.Item label="坐席工号">
              {currentRecord.seatsNumber || '--'}
            </Descriptions.Item>
          </Descriptions>
        </Modal>
        <SeatOperation
          ref={SeatOperationRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
      </div>
    );
  }
}
